<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>单刷数据查询</title>
    <script src="/static/js/echarts.min.js"></script>
    <style>
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
        }
        .form-container, .chart-container {
            width: 95%;
            margin: 20px auto;
            padding: 30px;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            transition: all 0.3s ease;
        }
        .form-container:hover, .chart-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        #queryForm {
            display: flex;
            flex-wrap: wrap;
        }
        #queryForm div {
            margin: 15px 10px;
            display: inline-flex;
            align-items: center;
            flex: 1 1 auto;
        }
        #queryForm div:last-child {
            flex-basis: 100%;
            margin: 15px 0;
        }
        #queryForm label {
            width: 60px;
            font-weight: 500;
            color: #4a5568;
        }
        #queryForm input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s ease;
        }
        #queryForm input:focus {
            outline: none;
            border-color: #3182ce;
            box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1);
        }
        #queryForm button {
            width: 100%;
            padding: 10px;
            background-color: #3182ce;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        #queryForm button:hover {
            background-color: #2c5282;
        }
        .chart {
            width: 100%;
            height: 400px;
            margin: 20px 0;
            border: 2px solid;
            border-radius: 8px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        #etaChart {
            border-color: #5470C6;
        }
        #iscChart {
            border-color: #91CC75;
        }
        #ffChart {
            border-color: #FAC858;
        }
        #uocChart {
            border-color: #EE6666;
        }
    </style>
    <style>
        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3182ce;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
            display: none;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="form-container">
            <h2>单刷数据查询</h2>
            <form id="queryForm">
                <div>
                    <label>年份：</label>
                    <input type="number" id="year" value="2025" required>
                </div>
                <div>
                    <label>月份：</label>
                    <input type="number" id="month" min="1" max="12" value="5">
                </div>
                <div>
                    <label>日期：</label>
                    <input type="number" id="day" min="1" max="31" value="16" required>
                </div>
                <div>
                    <label>线别：</label>
                    <input type="text" id="line" value="16B" required>
                </div>
                <div>
                    <label>班次：</label>
                    <input type="text" id="shift" value="N" required>
                </div>
                <button type="submit">查询</button>
            </form>
        </div>
        <div class="info-container" style="display: none;">
    <p>查询信息：<span id="queryInfo"></span> | 查询时间：<span id="queryTime"></span></p>
</div>
<div class="loader" id="loadingSpinner"></div>
<div class="chart-container">
            <div id="etaChart" class="chart"></div>
            <div id="iscChart" class="chart"></div>
            <div id="ffChart" class="chart"></div>
            <div id="uocChart" class="chart"></div>
        </div>
    </div>
    <script>
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const currentTime = hours * 60 + minutes;
        let shift = 'D';
        let date = now.getDate();
        let month = now.getMonth() + 1;
        let year = now.getFullYear();

        if (currentTime >= 1230 || currentTime < 510) {
            shift = 'N';
            if (currentTime >= 1230) {
                date = now.getDate();
            } else {
                const yesterday = new Date(now);
                yesterday.setDate(now.getDate() - 1);
                date = yesterday.getDate();
                month = yesterday.getMonth() + 1;
                year = yesterday.getFullYear();
            }
        }

        document.getElementById('year').value = year;
        document.getElementById('month').value = month;
        document.getElementById('day').value = date;
        document.getElementById('line').value = '1A';
        document.getElementById('shift').value = shift;

        const myCharts = {
            eta: echarts.init(document.getElementById('etaChart')),
            isc: echarts.init(document.getElementById('iscChart')),
            ff: echarts.init(document.getElementById('ffChart')),
            uoc: echarts.init(document.getElementById('uocChart'))
        };

        document.getElementById('queryForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            document.getElementById('loadingSpinner').style.display = 'block';
            const formData = {
                year: document.getElementById('year').value,
                month: document.getElementById('month').value,
                day: document.getElementById('day').value,
                line: document.getElementById('line').value,
                shift: document.getElementById('shift').value
            };

            try {
                const response = await fetch('/api/query', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('服务器返回了非JSON格式的数据');
                }
                const data = await response.json();
                console.log('获取到的数据:', data);
                document.getElementById('queryInfo').textContent = `${formData.year}-${formData.month}-${formData.day}-${formData.line}-${formData.shift}`;
                document.getElementById('queryTime').textContent = new Date().toLocaleString();
                document.querySelector('.info-container').style.display = 'block';
                renderCharts(data);
                document.getElementById('loadingSpinner').style.display = 'none';  // 添加这行代码
            } catch (error) {
                console.error('获取数据失败:', error);
                document.getElementById('loadingSpinner').style.display = 'none';
                alert('数据加载失败，请检查网络连接并确保后端服务正在运行');
                document.querySelector('.info-container').style.display = 'none';
                Object.values(myCharts).forEach(chart => chart.clear());
            }
        });

        function movingAverage(data, windowSize = 250) {
            if (typeof windowSize !== 'number' || windowSize <= 0) {
                throw new Error('windowSize必须是大于0的数字');
            }
            return data.map((_, index, arr) => {
                if (typeof index !== 'number' || index < 0) {
                    throw new Error('index必须是大于等于0的数字');
                }
                const start = Math.max(0, index - windowSize + 1);
                const end = index + 1;
                const subset = arr.slice(start, end);
                return subset.reduce((sum, value) => sum + value, 0) / subset.length;
            });
        }

        function renderCharts(data) {
            console.log('原始数据:', data);
            if (!Array.isArray(data)) {
                console.error('数据格式错误：期望数组，实际得到', typeof data);
                if (data && typeof data === 'object') {
                    data = [data];
                } else {
                    return;
                }
            }
            // 使用 map 方法提取每个对象的 eta 值
            const etaValues = data.map(item => item.eta);
            const uocValues = data.map(item => item.uoc);
            const iscValues = data.map(item => item.isc);
            const ffValues = data.map(item => item.ff);

            // 输出结果，查看提取的 eta 值数组
                eta=movingAverage(etaValues);
                isc=movingAverage(iscValues);
                ff=movingAverage(ffValues);
                uoc=movingAverage(uocValues);

            const optionTemplate = {
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'value',
                    min: 0,
                    max: 60000,
                    interval: 5000
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    data: [],
                    type: 'line'
                }]
            };

            myCharts.eta.setOption({
                ...optionTemplate,
                title: { text: 'ETA趋势图' },
                yAxis: {
                    type: 'value',
                    name: 'ETA',
                    min: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg - 0.3;
                    },
                    max: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg + 0.3;
                    },
                    splitLine: { show: false }
                },
                series: [{
                    ...optionTemplate.series[0],
                    data: eta.map((value, index) => [index, value]),
                    lineStyle: {
                        color: '#5470C6',
                        width: 2
                    },
                    showSymbol: false,
                    smooth: true
                }]
            });

            myCharts.isc.setOption({
                ...optionTemplate,
                title: { text: 'ISC趋势图' },
                yAxis: {
                    type: 'value',
                    name: 'ISC',
                    min: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg - 0.05;
                    },
                    max: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg + 0.05;
                    },
                    splitLine: { show: false }
                },
                series: [{
                    ...optionTemplate.series[0],
                    data: isc.map((value, index) => [index, value]),
                    lineStyle: {
                        color: '#91CC75',
                        width: 2
                    },
                    showSymbol: false,
                    smooth: true
                }]
            });

            myCharts.ff.setOption({
                ...optionTemplate,
                title: { text: 'FF趋势图' },
                yAxis: {
                    type: 'value',
                    name: 'FF',
                    min: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg - 0.5;
                    },
                    max: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg + 0.5;
                    },
                    splitLine: { show: false }
                },
                series: [{
                    ...optionTemplate.series[0],
                    data: ff.map((value, index) => [index, value]),
                    lineStyle: {
                        color: '#FAC858',
                        width: 2
                    },
                    showSymbol: false,
                    smooth: true
                }]
            });

            myCharts.uoc.setOption({
                ...optionTemplate,
                title: { text: 'UOC趋势图' },
                yAxis: {
                    type: 'value',
                    name: 'UOC',
                    min: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg - 0.005;
                    },
                    max: function(value) {
                        const avg = (value.min + value.max) / 2;
                        return avg + 0.005;
                    },
                    splitLine: { show: false }
                },
                series: [{
                    ...optionTemplate.series[0],
                    data: uoc.map((value, index) => [index, value]),
                    lineStyle: {
                        color: '#EE6666',
                        width: 2
                    },
                    showSymbol: false,
                    smooth: true
                }]
            });
        }
    </script>
</body>
</html>